class dbField(object):
    def __init__(self,name):
        self.name=name

class dbMapping(object):
    def __init__(self,name,table):
        self.name=name
        self.table=table

class dbDatabase(dict):
    def __init__(self,cursor):
        self.cursor=cursor
    def doImport(self,obj):
        self[obj.__name__]=obj.load(self.cursor,self)
        setattr(self,obj.__name__,self[obj.__name__])

class dbObject(object):
    def __init__(self,db,**kw):
        global dbRegistry
        for k,v in type(self).__dict__.items():
            if isinstance(v,dbField):
                setattr(self,k,kw[v.name])
            elif isinstance(v,dbMapping):
                if kw[v.name]:
                    setattr(self,k,db[v.table][kw[v.name]])
                else:
                    setattr(self,k,None)

    def __repr__(self):
        return '<%s %s>'%(type(self).__name__,' '.join(('%s=%r'%(k,v) for (k,v) in self.__dict__.items() if hasattr(type(self),k))))

    @classmethod
    def load(cls,curs,db):
        curs.execute('SELECT * FROM %s'%cls.table)
        fields=[x[0] for x in curs.description]
        if hasattr(cls,'id'):
            key=cls.id.name
        else:
            key=fields[0]
        result={}
        for x in curs.fetchall():
            row=dict(zip(fields,x))
            row=cls(db,**row)
            result[row.id]=row
        print ' - Load form %r type %r - %d items.'%(cls.table,cls.__name__,len(result))
        return result
